package main

import (
	"fmt"
	"time"

	"github.com/fsnotify/fsnotify"

	"github.com/spf13/viper"
)

type ServerConfig struct {
	Name      string      `mapstructure:"name"`
	MysqlInfo MysqlConfig `mapstructure:"mysql"`
}
type MysqlConfig struct {
	Host string `mapstructure:"host"`
	Port int    `mapstructure:"port"`
}

func getEnvInfo(env string) string {
	viper.AutomaticEnv()
	return viper.GetString(env)
}

func main() {

	debug := getEnvInfo("Debug")
	fmt.Println("env:", debug)

	var configFileName string
	var configFileNamePrefix = "config"
	if debug == "true" {
		configFileName = fmt.Sprintf("microservice/viper/%s-debug.yaml", configFileNamePrefix)
	} else {
		configFileName = fmt.Sprintf("microservice/viper/%s-prod.yaml", configFileNamePrefix)
	}

	v := viper.New()
	serverConfig := ServerConfig{}

	//添加读取的配置文件路径
	//v.AddConfigPath("./config/")
	//windows环境下为%GOPATH，linux环境下为$GOPATH
	//v.AddConfigPath("$GOPATH/src/")
	//设置配置文件类型
	//v.SetConfigType("yaml")

	v.SetConfigFile(configFileName)
	if err := v.ReadInConfig(); err != nil {
		panic(err)
	}

	if err := v.Unmarshal(&serverConfig); err != nil {
		panic(err)
	}
	fmt.Println(serverConfig)
	fmt.Println("name:", v.Get("name"))

	go func() {
		v.WatchConfig()
		v.OnConfigChange(func(e fsnotify.Event) {
			fmt.Println("Config file changed:", e.Name)
			if err := v.ReadInConfig(); err != nil {
				panic(err)
			}
			if err := v.Unmarshal(&serverConfig); err != nil {
				panic(err)
			}
			fmt.Println(serverConfig)
			fmt.Println("name:", v.Get("name"))
		})
	}()
	time.Sleep(time.Second * 300)

}
